package com.beta.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.beta.dto.order.OrderItemDto;
import com.beta.mapper.OrdersMapper;
import com.beta.service.IOrderItemsService;
import com.beta.service.ServiceException;
import com.beta.dto.order.OrdersDto;
import com.beta.service.ISalesService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by vector on 2016/12/8.
 */
@Service
public class SalesService implements ISalesService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private IOrderItemsService orderItemsService;

    @Override
    public Page<OrdersDto> getAssigningSalesOrders(Integer userId, Page<OrdersDto> page){
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = ordersMapper.getAssigningSalesOrders(page, userId);
        return salesPage(ordersDtos, page);
    }

    @Override
    public Page<OrdersDto> getDeliveringSalesOrders(Integer userId, Page<OrdersDto> page) {
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = ordersMapper.getDeliveringSalesOrders(page, userId);
        return salesPage(ordersDtos, page);
    }

    @Override
    public Page<OrdersDto> getCompleteSalesOrders(Integer userId, Page<OrdersDto> page) {
        if(Objects.isNull(userId)){
            throw new ServiceException("E00113");
        }
        List<OrdersDto> ordersDtos = ordersMapper.getCompleteSalesOrders(page, userId);
        return salesPage(ordersDtos, page);
    }

    private Page<OrdersDto> salesPage(List<OrdersDto> ordersDtos, Page<OrdersDto> page) {
        if (CollectionUtils.isEmpty(ordersDtos)) {
            return page;
        }

        List<Integer> orderIds = ordersDtos.stream().map(OrdersDto::getId).collect(Collectors.toList());
        Map<Integer, List<OrderItemDto>> orderOrderItemsMap = orderItemsService.getOrdersItemsBatchByOrderIds(orderIds);
        ordersDtos.forEach(ordersDto -> {
            ordersDto.setOrderItems(orderOrderItemsMap.get(ordersDto.getId()));
        });
        page.setRecords(ordersDtos);
        return page;
    }

}
